{% extends "admin/change_form.html" %}
{% load dajaxice_templatetags %}
{% load i18n %}
{% spaceless %}

{% block extrastyle %}
{{ block.super }}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.css" rel="stylesheet">
<link href="{{ STATIC_URL }}css/bootstrap-checkbox.css" rel="stylesheet">
<!-- <link href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" rel="stylesheet"> -->

{% endblock %}

{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-latest.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap-checkbox.js"></script>
<!-- <script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script> -->
<!-- <script type="text/javascript" src="{{ STATIC_URL }}js/TableTools.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
	$('fieldset table .original p').remove();
	$('input[type="checkbox"]').checkbox({
		buttonStyle: 'btn-link btn-lg',
		checkedClass: 'fa fa-check-square-o',
		uncheckedClass: 'fa fa-square-o',
	});
	//$('#table_pre').dataTable();
});
</script>

{% dajaxice_js_import %}
{% endblock %}

{% block pretitle %}<h1>{{original}}</h1>{% endblock %}
{% block content_title %}
<span class="label label-warning">Warning</span> Data exporting is only work correctly in Google Chrome and FireFox.
{% endblock %}

{% block content %}
<div class="page-header"></div>
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<a class="btn btn-primary " id="btnSignupOnly">{% trans "Signup data preset" %}</a>
			<a class="btn btn-primary " id="btnRecordOnly">{% trans "Record data preset" %}</a>
			<a class="btn btn-primary " id="btnClearAll">{% trans "Clear all" %}</a>
			<a class="btn btn-success disabled" id="btnExport">Exprt</a>
		</div>
	</div>
	<div class="row">
		<div class="col-md-4">
				<div class="row">
					<div class="col-md-12">
						<h4>{% trans "Event information" %}</h4>
					</div>
				</div>
				<form class="form-horizontal" id="exportFrom" method="POST">
				{% csrf_token %}
				<input type="hidden" name="event_id" value="{{original.id}}"/>
				<input type="hidden" name="eventinfoKeys_id"/>
				<input type="hidden" name="participantKeys_id"/>
				<div class="row">
					<div class="col-md-6">
						{% for fieldset in adminform %}
							{% for line in fieldset %}
								{% if forloop.counter0|divisibleby:"2" == 1 %}
									{% for field in line %}
										<input type="checkbox" class="small" name="eventinfo_{{ field.field.name }}" data-label="{{ field.field.label }}"/>
									{% endfor %}
								{% endif %}
							{% endfor %}
						{% endfor %}
					</div>
					<div class="col-md-6">
						{% for fieldset in adminform %}
							{% for line in fieldset %}
								{% if forloop.counter0|divisibleby:"2" == 0 %}
									{% for field in line %}
										<input type="checkbox" class="small" name="eventinfo_{{ field.field.name }}" data-label="{{ field.field.label }}"/>
									{% endfor %}
								{% endif %}
							{% endfor %}
						{% endfor %}
					</div>
				</div>
				<div class="row">
					<div class="col-md-12">
						<h4>{% trans "Participants information" %}</h4>
					</div>
				</div>
				<div class="row">
					<div class="col-md-6">
					{% for inline_admin_formset in inline_admin_formsets %}
						{% for fieldsets in inline_admin_formset.fieldsets %}
								{% for fieldset in fieldsets %}
									{% for fields, v in fieldset.iteritems %}
										{% for field in v %}
											{% if forloop.counter0|divisibleby:"2" == 0 %}
											<input type="checkbox" class="small" name="participant_{{field}}" data-label="{{field|capfirst}}"/>
											{% endif %}
										{% endfor %}
									{% endfor %}
								{% endfor %}
						{% endfor %}
					{% endfor %}
					</div>
					<div class="col-md-6">
					{% for inline_admin_formset in inline_admin_formsets %}
						{% for fieldsets in inline_admin_formset.fieldsets %}
								{% for fieldset in fieldsets %}
									{% for fields, v in fieldset.iteritems %}
										{% for field in v %}
											{% if forloop.counter0 != 0 and forloop.counter0|divisibleby:"2" == 1 %}
											<input type="checkbox" class="small" name="participant_{{field}}" data-label="{{field|capfirst}}"/>
											{% endif %}
										{% endfor %}
									{% endfor %}
								{% endfor %}
						{% endfor %}
					{% endfor %}
					</div>
				</div>
			</form>
		</div>
		<div class="col-md-6">
			<iframe name="Right" src="" style="visibility:hidden;display:none"></iframe>
			<div class="row">
				<div class="col-md-12">
					<h4>{% trans "Export preview" %} <img id="loadinggif" src="{{ STATIC_URL }}img/loading.gif" height="24" width="24" style="display:none;"></h4>
				</div>
			</div>
			<div class="row">
				<div class="col-md-12">
					<table class="table_preview" id="table_pre">
						<thead>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
			
		</div>
	</div>
</div>

<script type="text/javascript">
var gEventColStr = "";
var gPartiColStr = "";
var gQuerySet = false;
$(document).ready(function(){
	$('#btnExport').on('click', function (event) {
		if( $(this).hasClass('disabled') ) return;
		$('#exportFrom').prop('action', "/events/dataexport/");
		$('#exportFrom').prop('target', "Right");
		var ifr = document.getElementsByName("Right")[0];
        ifr.src = "/events/dataexport/";
		var resdl = [];
		resdl = getKeysLists();
		if( resdl[0].length ) $('input[name="eventinfoKeys_id"]').val(resdl[0]);
		if( resdl[1].length ) $('input[name="participantKeys_id"]').val(resdl[1]);
		$('#exportFrom').submit();
	});
	
	$('#btnSignupOnly').on('click', function(event){
		clearAll();
		gQuerySet = true;
		$('input[name="eventinfo_name"]').checkbox('click');
		$('input[name="eventinfo_date"]').checkbox('click');
		$('input[name="eventinfo_fieldName"]').checkbox('click');
		$('input[name="eventinfo_fieldAddress"]').checkbox('click');
		$('input[name="eventinfo_fee"]').checkbox('click');
		$('input[name="eventinfo_runnerLimit"]').checkbox('click');
		
		$('input[name="participant_name"]').checkbox('click');
		$('input[name="participant_pid"]').checkbox('click');
		$('input[name="participant_email"]').checkbox('click');
		$('input[name="participant_phoneNum"]').checkbox('click');
		$('input[name="participant_emgcyContact"]').checkbox('click');
		$('input[name="participant_emgcyContPhone"]').checkbox('click');
		$('input[name="participant_estimateTime"]').checkbox('click');
		
		gQuerySet = false;
		getTableReview();
	});
	$('#btnRecordOnly').on('click', function(event){
		clearAll();
		gQuerySet = true;
		$('input[name="eventinfo_name"]').checkbox('click');
		$('input[name="eventinfo_type"]').checkbox('click');
		$('input[name="eventinfo_umpires"]').checkbox('click');
		$('input[name="eventinfo_temperature"]').checkbox('click');
		$('input[name="eventinfo_humidity"]').checkbox('click');
		$('input[name="eventinfo_windSpeed"]').checkbox('click');
		
		$('input[name="participant_name"]').checkbox('click');
		$('input[name="participant_gender"]').checkbox('click');
		$('input[name="participant_serial"]').checkbox('click');
		$('input[name="participant_totalRank"]').checkbox('click');
		$('input[name="participant_genderRank"]').checkbox('click');
		$('input[name="participant_record"]').checkbox('click');
		$('input[name="participant_avgspeed"]').checkbox('click');
		$('input[name="participant_estimateTime"]').checkbox('click');
		gQuerySet = false;
		getTableReview();
	});
	$('#btnClearAll').on('click', function (event){
		gQuerySet = true;
		clearAll();
		gQuerySet = false;
		getTableReview();
	});
	$('input[type="checkbox"]').change(function() { getTableReview(); });
	
	function clearAll(){
		gQuerySet = true;
		$('input[type="checkbox"]').checkbox({checked: false});
		gQuerySet = false;
	};
	function getTableReview(){
		if( gQuerySet ) return;
		if( $('#btnExport').hasClass('disabled') == false ) $('#btnExport').addClass('disabled');
		$('#loadinggif').show();
		
		data = $('#exportFrom').serialize();
		var el = [];
		var pl = [];
		var dl = data.split('&');
		var newData, i, v;
		newData = "";
		var resdl = [];
		resdl = getKeysLists();
		newData = resdl[2];
		if( resdl[0].length ) newData += ("&eventinfoKeys_id=" + resdl[0]);
		if( resdl[1].length ) newData += ("&participantKeys_id=" + resdl[1]);
		Dajaxice.events.eventDataExportJSON(resultCallback, {'form':newData}, {'error_callback': errorCallback});
	};//);
});

function getKeysLists()
{
	data = $('#exportFrom').serialize();
	var res = [];
	var el = [];
	var pl = [];
	var dl = data.split('&');
	var ed, pd, eld, i, v;
	ed = "";
	pd = "";
	eld = "";
	for( i in dl )
	{
		v = dl[i];
		if( v.indexOf("eventinfo_") == 0 )
		{
			en = v.slice(("eventinfo_").length, v.indexOf("="));
			el[getELI(en)] = en;
		}
		else if( v.indexOf("participant_") == 0 )
		{
			pn = v.slice(("participant_").length, v.indexOf("="));
			pl[getPLI(pn)] = pn;
		}
		else if( v.indexOf("eventinfoKeys_id") == 0 || v.indexOf("participantKeys_id") == 0 ) {}
		else eld += (v + "&");
	}
	for( i in el ) ed += (el[i] + "_");
	for( i in pl ) pd += (pl[i] + "_");
	if( ed.length ) ed = ed.slice(0, ed.length-1);
	if( pd.length ) pd = pd.slice(0, pd.length-1);
	if( eld.length ) eld = eld.slice(0, eld.length-1);
	res[0] = ed;
	res[1] = pd;
	res[2] = eld;
	return res;
}

function getELI(pn)
{
	var elo = [
	{% for fieldset in adminform %}{% for line in fieldset %}{% for field in line %}"{{field.field.name}}",{% endfor %}{% endfor %}{% endfor %}
	];
	return elo.indexOf(pn);
}
function getPLI(pn)
{
	var plo = [
	{% for inline_admin_formset in inline_admin_formsets %}{% for fieldsets in inline_admin_formset.fieldsets %}{% for fieldset in fieldsets %}{% for fields, v in fieldset.iteritems %}{% for field in v %}"{{field}}",{% endfor %}{% endfor %}{% endfor %}{% endfor %}{% endfor %}
	];
	return plo.indexOf(pn);
}

function resultCallback(data)
{	
	// clear
	$('.table_preview tbody').empty();
	
	// check must has columns property
	if(!data.hasOwnProperty("columns"))
	{
		createTableFinish()
        alert("need property - columns");
		return;
    }
	if( data["columns"].length == 0 )
	{
		createTableFinish()
		return;
	}
	
	// enable export
	$('#btnExport').removeClass('disabled');
	
	// create columns
	var cn, evn, pn;
	var enl = [];
	var	pnl = [];
	for( var c in data["columns"] )
	{
		cn = data["columns"][c];
		if( cn.indexOf("eventinfo_")==0)
		{
			evn = cn.slice(("eventinfo_").length, cn.length);
			enl[getELI(evn)] = evn;
		}
		else if( cn.indexOf("participant_")==0)
		{
			pn = cn.slice(("participant_").length, cn.length);
			pnl[getPLI(pn)] = pn;
		}
	}
	
	gEventColStr = "";
	for( k in enl )
	{
		if( $('.table_preview tbody tr.event_info_title').length == 0 ) $('.table_preview tbody').append('<tr class="event_info_title"></tr>');
		$('.table_preview tbody tr.event_info_title').append('<td class="event_'+enl[k]+'" style="font-weight:bold">' + enl[k] + '</td>');
		gEventColStr += (enl[k] + "_");
	}
	if( gEventColStr.length > 1 ) gEventColStr = gEventColStr.slice(0, gEventColStr.length-1);
	
	gPartiColStr = "";
	for( k in pnl )
	{
		if( $('.table_preview tbody tr.participant_info_title').length == 0 ) $('.table_preview tbody').append('<tr class="participant_info_title"></tr>');
		$('.table_preview tbody tr.participant_info_title').append('<td class="parti_'+pnl[k]+'" style="font-weight:bold">' + pnl[k] + '</td>');
		gPartiColStr += (pnl[k] + "_");
	}
	if( gPartiColStr.length > 1 ) gPartiColStr = gPartiColStr.slice(0, gPartiColStr.length-1);
			
	$('.table_preview tbody tr.event_info_title').after('<tr class="event_info"></tr>');
	$('.table_preview tbody tr.participant_info_title').after('<tr class="participant_info_0"></tr>');
	
	// fill event info columns
	var ed = [];
	var pd = [];
	for( k in data )
	{	
		if( k.indexOf("eventinfo_") == 0 )
		{
			cn = k.slice(("eventinfo_").length, k.length);
			ed[enl.indexOf(cn)] = data[k];
		}
		else if( k.indexOf("participant_") == 0 )
		{
			pn = k.slice(("participant_").length, k.length);
			pd[pn] = data[k]
		}
	}
	
	for( k in ed )
	{
		pistr = (ed[k]) == null ? "" : (ed[k]);
		$('.event_info').append('<td>'+pistr+'</td>');
	}
	
	for( k in pd )
	{
		curC = ".participant_info_" +k.toString();
		for( var pi in pd[k] )
		{
			pistr = (pd[k][pi]) == null ? "" : (pd[k][pi]);
			$(curC).append('<td>'+ pistr +'</td>');
		}
		$(curC).after('<tr class="participant_info_'+ (parseInt(k)+1).toString() +'"></tr>');
	}
	
	
	createTableFinish()
}

function errorCallback()
{
	$('#loadinggif').hide();
	console.log('data export ajax error');
}

function createTableFinish()
{
	$('#loadinggif').hide();
	$('#exportProgress ').removeClass('progress-striped active');
}
</script>
{% endblock %}
{% endspaceless %}